package com.vehicle.auto.click.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(
        basePackages = {"com.vehicle.auto.click.mapper.second"},
        sqlSessionTemplateRef = "secondSqlSessionTemplate"
)
public class DataSourceConfigSecond {
    @Bean(
            name = {"secondDataSource"}
    )
    @ConfigurationProperties(
            prefix = "spring.datasource.second"
    )
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(
            name = {"secondSqlSessionFactory"}
    )
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations((new PathMatchingResourcePatternResolver()).getResources("classpath*:mapper/*.xml"));
        return bean.getObject();
    }

    @Bean(
            name = {"secondTransactionManager"}
    )
    public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(
            name = {"secondSqlSessionTemplate"}
    )
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
